package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripComment;
import cn.itrip.beans.pojo.ItripImage;
import cn.itrip.beans.vo.ItripImageVO;
import cn.itrip.beans.vo.comment.ItripListCommentVO;
import cn.itrip.beans.vo.comment.ItripSearchCommentVO;
import cn.itrip.common.*;
import cn.itrip.service.itripComment.ItripCommentService;
import cn.itrip.service.itripImage.ItripImageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName HotelSystemComment
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2021/1/11 14:55
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/comment")
public class HotelSystemComment {


    @Autowired
    private ItripCommentService itripCommentService;

    @Autowired
    private ItripImageService itripImageService;


    @Autowired
    private SystemConfig systemConfig;


    @RequestMapping(value = "/getimg/{targetId}",method = RequestMethod.GET,produces = "application/json")
    public Dto<List<ItripImageVO>> getImg(@PathVariable String targetId){
            //封装请求数据
       Map map = new HashMap<>();
       map.put("targetId",targetId);
       map.put("type",2);

            //2.调用service获取图片路径
        try {
          List<ItripImage> itripImageList=itripImageService.getItripImageListByMap(map);

            //3.pojo--->vo
           List<ItripImageVO> itripImageVOList=new ArrayList<ItripImageVO>();
            for (ItripImage itripimage:itripImageList) {
                ItripImageVO itripImageVO = new ItripImageVO();
                BeanUtils.copyProperties(itripimage,itripImageVO);
                itripImageVOList.add(itripImageVO);
            }
            //4.返回前端
          return DtoUtil.returnDataSuccess(itripImageVOList);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("SQLException", ErrorCode.SQL_ERROR);
        }
    }

    @RequestMapping(value = "/getcommentlist",method = RequestMethod.POST)
    public  Dto<Page> getCommentList(@RequestBody ItripSearchCommentVO itripSearchCommentVO ){
        //对入参数进行条件判断
        if(itripSearchCommentVO.getHotelId()==null
                || itripSearchCommentVO.getIsHavingImg()==null
                ||itripSearchCommentVO.getIsOk()==null
                ||itripSearchCommentVO.getPageNo()==null
                ||itripSearchCommentVO.getPageSize()==null){
            return  DtoUtil.returnFail("参数异常",ErrorCode.HOTEL_ILLEGAL_ARGS);
        }
        //对参数进行处理   因为dao层动态sql,设置为null则可以查询全部
        if(itripSearchCommentVO.getIsOk()==-1);itripSearchCommentVO.setIsOk(null);
        if(itripSearchCommentVO.getIsHavingImg()==-1);itripSearchCommentVO.setIsHavingImg(null);


        //调用service接口查询
        Map map = new HashMap();
        map.put("hotelId",itripSearchCommentVO.getHotelId());
        map.put("isHavingImg",itripSearchCommentVO.getIsHavingImg());
        map.put("isOk",itripSearchCommentVO.getIsOk());
        //分页查询数据
        try {
            Page page =itripCommentService.queryItripCommentPageByMap(map,itripSearchCommentVO.getPageNo(),itripSearchCommentVO.getPageSize());
          return   DtoUtil.returnDataSuccess(page);
        } catch (Exception e) {
            e.printStackTrace();
            return  DtoUtil.returnFail("sqlException",ErrorCode.SQL_ERROR);
        }
    }

    @RequestMapping(value = "/upload",method =RequestMethod.POST)
    public Dto<List<String>> upload(HttpServletRequest request, HttpServletResponse response){
        List<String> result=new ArrayList<>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)){
            //处理文件上传
            MultipartHttpServletRequest mutipartRequest =(MultipartHttpServletRequest)request;
          int count= mutipartRequest.getMultiFileMap().size();
          if(count<=4){
              //读文件
              // 获取文件名称，文件类型
              //验证文件类型
              //保存文件，不用原名称
              //存到服务器指定目录
            Iterator<String> names= mutipartRequest.getFileNames();
            while(names.hasNext()){
                String originalFileName=null;
                //根据名称获取文件
                MultipartFile file =mutipartRequest.getFile(names.next());
                if(file!=null){
                    //后缀验证，判断文件类型
                   originalFileName= file.getOriginalFilename();  //aaa.png

                   String suffix=originalFileName.substring(originalFileName.lastIndexOf("."));
                   if(suffix.equals(".png")||suffix.equals(".jpg")||suffix.equals(".jpeg")||suffix.equals(".pneg")){
                         //生成一个新的文件名称 userID+当前系统时间戳+随机数
                       String fileName="token_userid"+"-"+System.currentTimeMillis()+"-"+ MD5.getRandomCode()+suffix;
                        //完整的保存路径
                    String fullPath=systemConfig.getFileUploadPathString()+ File.separator+""+fileName;

                    //传输
                       try {
                           file.transferTo(new File(fullPath));
                           result.add(systemConfig.getVisitImgUrlString()+fileName);
                       } catch (IOException e) {
                           e.printStackTrace();
                       }

                       //返回文件上传的路径

                   }
                }
            }
            return  DtoUtil.returnDataSuccess(result);
          }else{
              return  DtoUtil.returnFail("上传图片数量不能多于4张",ErrorCode.IMAGE_OUTOF_BOUND_EXCEPTION);
          }
        }
        return  DtoUtil.returnFail("没有文件",ErrorCode.NO_IMAGE_EXCEPTION);

    }










}
